package com.ztky.report.scriptlet;

import net.sf.jasperreports.engine.JRDefaultScriptlet;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JRScriptletException;
import net.sf.jasperreports.functions.annotations.Function;
import net.sf.jasperreports.functions.annotations.FunctionCategories;
import net.sf.jasperreports.functions.annotations.FunctionParameter;
import net.sf.jasperreports.functions.annotations.FunctionParameters;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.*;

@FunctionCategories({ HmsScriptletUtils.class })
public class HmsScriptletUtils extends JRDefaultScriptlet {

//	private static final Logger log = LoggerFactory.getLogger(HmsScriptletUtils.class);

	public void afterReportInit() throws JRScriptletException {
		// this.setVariableValue("someVar", new String("This variable value was modified
		// by the scriptlet."));
	}

	/**
	 * 格式化药物过敏史
	 * 
	 * @return
	 * @throws JRScriptletException
	 */
	@Function("formatDrugAllergy")
	@FunctionParameters({ @FunctionParameter("allergy"), @FunctionParameter("other") })
	public String formatDrugAllergy(String allergy, String other) throws JRScriptletException {
		if (allergy == null || allergy.length() == 0) {
			return allergy;
		}
		StringBuffer sb = new StringBuffer();
		if (allergy.contains("0")) {
			sb.append("无");
		}
		if (allergy.contains("1")) {
			if (sb.length() > 0) {
				sb.append(",");
			}
			sb.append("青霉素");
		}
		if (allergy.contains("2")) {
			if (sb.length() > 0) {
				sb.append(",");
			}
			sb.append("磺胺");
		}
		if (allergy.contains("3")) {
			if (sb.length() > 0) {
				sb.append(",");
			}
			sb.append("链霉素");
		}
		if (allergy.contains("5")) {
			if (other != null) {
				if (sb.length() > 0) {
					sb.append(",");
				}
				sb.append(other);
			}
		}
		return sb.toString();
	}

	/**
	 * 格式化暴露史
	 * 
	 * @param history
	 * @return
	 * @throws JRScriptletException
	 */
	@Function("formatExposureHistory")
	@FunctionParameters({ @FunctionParameter("history") })
	public String formatExposureHistory(String history) throws JRScriptletException {
		if (history == null || history.length() == 0) {
			return history;
		}
		StringBuffer sb = new StringBuffer();
		if (history.contains("1")) {
			sb.append("无");
		}
		if (history.contains("2")) {
			if (sb.length() > 0) {
				sb.append(",");
			}
			sb.append("化学品");
		}
		if (history.contains("3")) {
			if (sb.length() > 0) {
				sb.append(",");
			}
			sb.append("毒物");
		}
		if (history.contains("4")) {
			if (sb.length() > 0) {
				sb.append(",");
			}
			sb.append("射线");
		}

		return sb.toString();
	}

	public boolean isEmpty(String str) {
		if (str == null || str.trim().length() == 0) {
			return true;
		}
		return false;
	}

	@Function("formatFamily")
	@FunctionParameters({ @FunctionParameter("father1"), @FunctionParameter("father2"), @FunctionParameter("father3") })
	public String formatFamily(String father1, String father2, String father3) throws JRScriptletException {
		if (father1 == null && father2 == null && father3 == null) {
			return "";
		}
		StringBuffer sb = new StringBuffer();
		if (!isEmpty(father1)) {
			sb.append(father1);
		}
		if (!isEmpty(father2)) {
			if (sb.length() > 0) {
				sb.append(",");
			}
			sb.append(father2);
		}
		if (!isEmpty(father3)) {
			if (sb.length() > 0) {
				sb.append(",");
			}
			sb.append(father3);
		}
		return sb.toString();
	}

	/**
	 * 
	 * @param conn
	 * @param sql
	 * @param function
	 * @return
	 */
	private Connection conn = null;

	private String query(String sql, java.util.function.Function<List<Map<String, Object>>, String> function) {
		Statement statement = null;
		ResultSet rs = null;
		Connection conn = null;
		try {
			conn = this.conn;
			if (conn == null) {
				conn = (Connection) this.getParameterValue(JRParameter.REPORT_CONNECTION);
			}
			// 3 定义sql 创建状态通道(进行sql语句的发送)
			statement = conn.createStatement();
			rs = statement.executeQuery(sql);
			List<Map<String, Object>> result = new ArrayList<>();
			while (rs.next()) {
				Map<String, Object> map = new HashMap<>();
				ResultSetMetaData meta = rs.getMetaData();
				for (int i = 1; i <= meta.getColumnCount(); i++) {
					map.put(meta.getColumnName(i), rs.getObject(i));
				}
				result.add(map);
			}
			// 4 取出结果集
			return function.apply(result);
		} catch (JRScriptletException | SQLException throwables) {
			// } catch (SQLException throwables) {
			throwables.printStackTrace();
		}
		// TODO 非常重要，在scriptlet类里不能关闭conn等操作，不然主报表就会出错
		// finally {
		// try {
		// if (rs != null) {
		// rs.close();
		// }
		// if (statement != null) {
		// statement.close();
		// }
		// if (conn != null) {
		// conn.close();
		// }
		// } catch (SQLException throwables) {
		// throwables.printStackTrace();
		// }
		// }
		return null;
	}

	@Function("formatDateTime")
	@FunctionParameters({ @FunctionParameter("date"), @FunctionParameter("format") })
	public String formatDateTime(Object date, String format) {
		if (date == null) {
			return "未知";
		}
		if (format == null) {
			format = "yyyy-MM-dd";
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		if (date instanceof Date) {
			return sdf.format((Date) date);
		}
		if (date instanceof java.sql.Date) {
			return sdf.format((java.sql.Date) date);
		}
		if (date instanceof java.sql.Timestamp) {
			return sdf.format((java.sql.Date) date);
		}
		if (date instanceof LocalDateTime) {
			LocalDateTime dt = (LocalDateTime) date;
			return dt.format(DateTimeFormatter.ofPattern(format));
		}
		return null;

	}

	/**
	 * 查询疾病既往史
	 * 
	 * @param conn
	 * @param guestId
	 * @return
	 */
	@Function("queryPastDisease")
	@FunctionParameters({ @FunctionParameter("guestId") })
	public String queryPastDisease(Integer guestId) {
		if (guestId == null) {
			return "";
		}
		String sql = "select id, guest_id, `name`, trauma_time  from health_basic_anamnesis WHERE guest_id=" + guestId;

		return this.query(sql, (rs) -> {
			try {
				Set<String> set = new HashSet<>();
				for (Map<String, Object> map : rs) {
					StringBuffer sb = new StringBuffer();
					sb.append((String) map.get("name")).append(" ").append("确诊时间：");
					Object tt = map.get("trauma_time");
					if (tt != null) {
						sb.append(formatDateTime(tt, "yyyy年MM月"));
					} else {
						sb.append("未知");
					}
					set.add(sb.toString());
				}
				if (set.size() == 0) {
					return "无";
				} else {
					return String.join("/", set);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		});
	}

//1无  2高血压  3糖尿病  4冠心病  5慢性阻塞性肺疾病  6恶性肿瘤  7脑卒中
// 8严重精神障碍  9结核病  10肝炎  11先天畸形  12其他
	private transient Map<String, String> familyDisease = new HashMap<String, String>() {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		{
			put("0", "无");
			put("1", "高血压");
			put("2", "糖尿病");
			put("3", "冠心病");
			put("4", "慢性阻塞性肺疾病");
			put("5", "帕金森");
			put("6", "骨质疏松症");
			put("7", "高尿酸血症");
			put("8", "恶性肿瘤");
			put("9", "脑卒中后遗症");
			put("10", "阿尔茨海默病");
			put("11", "严重精神障碍");
			put("12", "结核病 ");
			put("13", "肝炎");
			put("14", "先天畸形");
			put("99", "其他");
		}
	};

	/**
	 * 查询家族史
	 * 
	 * @param guestId
	 * @param relation
	 * @return
	 * @throws JRScriptletException
	 */
	@Function("queryFamilyDisease")
	@FunctionParameters({ @FunctionParameter("guestId"), @FunctionParameter("relation") })
	public String queryFamilyDisease(Integer guestId, String relation) throws JRScriptletException {
		if (guestId == null) {
			return "";
		}
		String sql = "SELECT t.id,t.guest_id,t.family_relation,t.`name`,t.chronic_disease FROM health_basic_family_disease AS t WHERE guest_id="
				+ guestId + "  and family_relation in (" + relation + ")";
//		log.info(sql);
		return this.query(sql, (rs) -> {
			try {
				Set<String> set = new HashSet<>();
				for (Map<String, Object> map : rs) {
					Object chronic_disease = map.get("chronic_disease");
					if (chronic_disease == null) {
						continue;
					}
					for (String id : ((String) chronic_disease).split(",")) {
						set.add(id);
						// set.add(familyDisease.get(id));
					}
				}
				if (set.size() == 0) {
					return "无";
				} else {
					return String.join(",", set);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		});
	}

	/**
	 * 查询手术史
	 * 
	 * @param guestId
	 * @return
	 * @throws JRScriptletException
	 */
	@Function("queryPastOperation")
	@FunctionParameters({ @FunctionParameter("guestId") })
	public String queryPastOperation(Integer guestId) throws JRScriptletException {
		if (guestId == null) {
			return "";
		}
		String sql = "SELECT	t.id,	t.guest_id,	t.`name`,	t.operation_time  FROM	health_basic_operation AS t WHERE	guest_id="
				+ guestId;
		return this.query(sql, (rs) -> {
			try {
				Set<String> set = new HashSet<>();
				for (Map<String, Object> map : rs) {
					Object chronic_disease = map.get("name");
					if (chronic_disease == null) {
						continue;
					}
					set.add("名称：" + (String) chronic_disease + " 时间："
							+ this.formatDateTime(map.get("operation_time"), "yyyy年MM月"));
				}
				if (set.size() == 0) {
					return "无";
				} else {
					return String.join("/", set);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		});
	}

	/**
	 * 查询外伤
	 * 
	 * @param guestId
	 * @return
	 */
	@Function("queryTrauma")
	@FunctionParameters({ @FunctionParameter("guestId") })
	public String queryTrauma(Integer guestId) {
		if (guestId == null) {
			return "";
		}
		String sql = "SELECT t.id,t.guest_id,t.`name`,t.trauma_time FROM health_basic_trauma AS t  WHERE	 guest_id="
				+ guestId;
		return this.query(sql, (rs) -> {
			try {
				Set<String> set = new HashSet<>();
				for (Map<String, Object> map : rs) {
					Object chronic_disease = map.get("name");
					if (chronic_disease == null) {
						continue;
					}
					set.add("名称：" + (String) chronic_disease + " 时间："
							+ this.formatDateTime(map.get("trauma_time"), "yyyy年MM月"));
				}
				if (set.size() == 0) {
					return "无";
				} else {
					return String.join("/", set);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		});
	}

	/**
	 * 查询输血
	 * 
	 * @param guestId
	 * @return
	 */
	@Function("queryBloodTrans")
	@FunctionParameters({ @FunctionParameter("guestId") })
	public String queryBloodTrans(Integer guestId) {
		if (guestId == null) {
			return "";
		}
		String sql = "SELECT t.id, t.guest_id,t.`name`,t.blood_transfusion_time FROM health_basic_blood_transfusion AS t  WHERE	 guest_id="
				+ guestId;
		return this.query(sql, (rs) -> {
			try {
				Set<String> set = new HashSet<>();
				for (Map<String, Object> map : rs) {
					Object chronic_disease = map.get("name");
					if (chronic_disease == null) {
						continue;
					}
					set.add("名称：" + (String) chronic_disease + " 时间："
							+ this.formatDateTime(map.get("blood_transfusion_time"), "yyyy年MM月"));
				}
				if (set.size() == 0) {
					return "无";
				} else {
					return String.join("/", set);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		});
	}

	/**
	 * 查询现病史
	 * 
	 * @param guestId
	 * @return
	 */
	@Function("queryCurrentDisease")
	@FunctionParameters({ @FunctionParameter("guestId") })
	public String queryCurrentDisease(Integer guestId) {
		if (guestId == null) {
			return "";
		}
		String sql = "SELECT t.id,t.guest_id,t.chronic_disease,t.disease_time FROM health_basic_anamnesis_disease AS t WHERE t.guest_id="
				+ guestId;
		return this.query(sql, (rs) -> {
			try {
				Set<String> set = new HashSet<>();
				for (Map<String, Object> map : rs) {
					Object chronic_disease = map.get("chronic_disease");
					if (chronic_disease == null) {
						continue;
					}
					if ("0".equals(chronic_disease)) {
						return "无";
					} else {
						set.add("名称：" + familyDisease.get((String) chronic_disease) + " 时间："
								+ this.formatDateTime(map.get("disease_time"), "yyyy年MM月"));
					}
				}
				if (set.size() == 0) {
					return "无";
				} else {
					return String.join("/", set);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		});
	}

//	public static void main(String[] args) {
//		String URL = "jdbc:mysql://10.0.1.33:3306/db_ztky_business";
//		String USER = "ljc";
//		String PASSWROD = "liu0769777";
//		Connection conn = null;
//		HmsScriptletUtils util = new HmsScriptletUtils();
//		try {
//			Class.forName("com.mysql.cj.jdbc.Driver");
//			// 获取数据库连接
//			conn = DriverManager.getConnection(URL, USER, PASSWROD);
//			util.conn = conn;
////			util.setParameterValue(JRParameter.REPORT_CONNECTION,conn);
//			System.out.println(util.queryPastDisease(399));
//		} catch (ClassNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}

}